#include <typescommon.h>
#include <genrand.h>
#include <pthread.h>
#include <threadExcuter.h>

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

pthread_mutex_t plock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pcond = PTHREAD_COND_INITIALIZER;
int globalVal = 0;

void *pfunc(void *data)
{
    pthread_t *intval = (pthread_t *)data;
    logdebug("thread=%lu begin", *intval);
    struct timespec tmpts;
    while (1)
    {
        // logdebug("thread=%lu run", *intval);
        clock_gettime(CLOCK_REALTIME, &tmpts);
        tmpts.tv_sec += 10;
        pthread_mutex_lock(&plock);
        // pthread_cond_wait(&pcond, &plock);//等待完成不一定是唤醒，要做globalVal判断。
        pthread_cond_timedwait(&pcond, &plock, &tmpts);//等待完成不一定是唤醒或超时，要做globalVal判断。
        if (globalVal)
        {
            logdebug("thread=%lu, val=%d", *intval, globalVal);
        }
        globalVal = 0;
        pthread_mutex_unlock(&plock);
    }
}

int main(int argc, char **argv)
{
    pthread_t tmpt[3];
    for (int i = 0; i < ARRAY_LEN(tmpt); i++)
    {
        pthread_create(&tmpt[i], NULL, pfunc, tmpt + i);
    }
    while (1)
    {
        logdebug("begin send val=%d", globalVal);
        pthread_mutex_lock(&plock);
        globalVal = 1;
        pthread_cond_signal(&pcond);//单个唤醒
        // pthread_cond_broadcast(&pcond);//全部唤醒
        pthread_mutex_unlock(&plock);
        sleep(5);
    }
    for (int i = 0; i < ARRAY_LEN(tmpt); i++)
    {
        pthread_join(tmpt[i], NULL);
    }
    return 1;
}
